package data;

public class Extramobi {
/*
    public static int catCount = 0;
    public static int counter = 0;

    public static final String NA = "уточняйте";
    public static final int COLUMNS = 8;

    public static String header;

    private static Map<String, Integer> catSort = new HashMap<String, Integer>();
    private static int record_count = 0;
    private static int file_count = 0;

    private static void checkCatSort(String cat) {
        if (!catSort.containsKey(cat)) {
            catSort.put(cat, Integer.parseInt(getSort()));
        }
    }

    public static void main(String[] args) throws IOException, BiffException {
        header = CSVData.getHeader();
        String outPath = "data/import/";
        Map<String, String> props = DataHelper.readProps("data/accums/accums.properties");

        PrintStream out = new PrintStream(new FileOutputStream(outPath + "extramobi-accums-nokia-price.txt"));
        out.println(header.toString());

        printAccums("data/accums/accum.nokia.txt", "Nokia", 1.25, props, true, outPath + "extramobi-accums-nokia-price", false, out);
        increaseCounter();
        printAccums("data/accums/accum.nokiamaxcell.txt", "NokiaMaxcell", 1, props, false, outPath + "extramobi-accums-nokia-maxcell-price", false, out);
        increaseCounter();
        printAccums("data/accums/accum.samsung.txt", "Samsung", 1, props, true, outPath + "extramobi-accums-samsung-price", true, null);
        increaseCounter();

        out.close();
        out = new PrintStream(new FileOutputStream(outPath + "extramobi-accums-se-lg.txt"));
        out.println(header.toString());
        printAccums("data/accums/accum.se.txt", "Sony Ericsson", 1, props, true, outPath + "extramobi-accums-se-price", false, out);
        increaseCounter();
        printAccums("data/accums/accum.lg.txt", "LG", 1, props, true, outPath + "extramobi-accums-lg-price", false, out);
        increaseCounter();

        out.close();
        out = new PrintStream(new FileOutputStream(outPath + "extramobi-accums-moto-htc-bb-apple-craf.txt"));
        out.println(header.toString());
        printAccums("data/accums/accum.motorola.txt", "Motorola", 1, props, true, outPath + "extramobi-accums-motorola-price", false, out);
        increaseCounter();
        printAccums("data/accums/accum.htc.txt", "HTC", 1, props, true, outPath + "extramobi-accums-htc-price", false, out);
        increaseCounter();
        printAccums("data/accums/accum.blackberry.txt", "Blackberry", 1, props, true, outPath + "extramobi-accums-blackberry-price", false, out);
        increaseCounter();
        printAccums("data/accums/accum.apple.txt", "Apple", 1, props, false, outPath + "extramobi-accums-apple-price", false, out);
        increaseCounter();
        printAccums("data/accums/accum.craftmann.txt", "Craftmann", 1, props, false, outPath + "extramobi-accums-craftmann-price", false, out);
        increaseCounter();

        props = DataHelper.readProps("data/chargers/chargers.properties");
        out.close();
        out = new PrintStream(new FileOutputStream(outPath + "extramobi-chargers-price.txt"));
        out.println(header);
        printCategory("chargers", props, out);
        printCategory("chargers.network", props, out);
        printChargers("chargers.network", "Nokia", props, out, 5, 1, false);
        increaseCounter();
        printChargers("chargers.network", "Samsung", props, out, 5, 1, false);
        increaseCounter();
        printChargers("chargers.network", "Sony Ericsson", props, out, 5, 1, false);
        increaseCounter();
        printChargers("chargers.network", "LG", props, out, 5, 1, false);
        increaseCounter();
        printChargers("chargers.network", "Blackberry", props, out, 5, 1, false);
        increaseCounter();
        printChargers("chargers.network", "HTC", props, out, 5, 1, false);
        increaseCounter();
        out.close();
        out = new PrintStream(new FileOutputStream(outPath + "extramobi-auto-chargers-price.txt"));
        out.println(header);
        printCategory("chargers", props, out);
        printCategory("chargers.auto", props, out);
        printChargers("chargers.auto", "Nokia", props, out, 5, 1, true);
        increaseCounter();
        printChargers("chargers.auto", "Samsung", props, out, 5, 1, true);
        increaseCounter();
        printChargers("chargers.auto", "Sony Ericsson", props, out, 5, 1, true);
        increaseCounter();
        printChargers("chargers.auto", "LG", props, out, 5, 1, true);
        increaseCounter();
        printChargers("chargers.auto", "Blackberry", props, out, 5, 1, true);
        increaseCounter();
        printChargers("chargers.auto", "HTC", props, out, 5, 1, true);
        increaseCounter();

        out = new PrintStream(new FileOutputStream(outPath + "extramobi-rest-price.txt"));
        out.println(header);

        props = DataHelper.readProps("data/holders/holders.properties");
        printCategory("holders", props, out);
        increaseCounter();

        props = DataHelper.readProps("data/cardreaders/cardreaders.properties");
        printCategory("cardreaders", props, out);
        increaseCounter();

        props = DataHelper.readProps("data/phones/cases.properties");
        printCategory("cases", props, out);
        increaseCounter();

        printCategory("covers", props, out);
        generateCovers(150);
        increaseCounter();

        props = DataHelper.readProps("data/body/bodies.properties");
        printCategory("bodies", props, out);
        printBodies("Nokia", props, out, 1);
        increaseCounter();
        printCategory("bodies", props, out);
        printBodies("Samsung", props, out, 1);
        increaseCounter();
        printCategory("bodies", props, out);
        printBodies("Sony Ericsson", props, out, 1);
        increaseCounter();
        out.close();

        out = new PrintStream(new FileOutputStream(outPath + "extramobi-headsets-price.txt"));
        props = DataHelper.readProps("data/headsets/headsets.properties");
        out.println(header);
        printCategory("cat", props, out);
        printHeadsets("Nokia", props, out);
        increaseCounter();
        printHeadsets("Sony Ericsson", props, out);
        increaseCounter();
        printHeadsets("Samsung", props, out);
        increaseCounter();
        out.close();

        printRepairs(10);
        increaseCounter(2);
    }

    private static void generateCovers(int price) throws IOException, BiffException {
        record_count = 0;
        ArrayList<String> brands = new ArrayList<String>();
        brands.add("Apple");
        brands.add("HTC");
        brands.add("Samsung");
        brands.add("Nokia");
        brands.add("Sony Ericsson");
        brands.add("LG");
        Map<String, String> props = DataHelper.readProps("data/phones/cases.properties");
//        printPhones(props, "data/import/covers-import.txt", price, "covers");
        String outPath = "data/import/covers-import.txt";
        PrintStream out = new PrintStream(new FileOutputStream(outPath));
        List<Repair> phones = ExcelParser.parseRepair("data/phones/phones.xls", price);
//        printHeader(out);
//        printCategory(props, prefix, out);
        for (Repair phone : phones) {
            if (!brands.contains(phone.vendor)) {
                continue;
            }
            if (record_count >= 1100) {
                record_count = 0;
                out.flush();
                out.close();
                out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
//                printHeader(out);
//                printCategory(props, prefix, out);
            }
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", phone.vendor);
            templates.put("\\$\\{brand\\.url\\}", phone.vendor);
            templates.put("\\$\\{url\\}", phone.vendor);
            Map<String, String> filteredProps = filterProps(props, templates);
//            printCategory(filteredProps, prefix + ".brand", out);
//            printPhone(filteredProps, phone, out, prefix);
        }

    }

*/
/*
     private static void printPhones(Map<String, String> props, String outPath, int price, String prefix) throws IOException, BiffException {
        PrintStream out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
        List<Repair> phones = ExcelParser.parseRepair("data/phones/phones.xls", price);
//        printHeader(out);
//        printCategory(props, prefix, out);
        for (Repair phone : phones) {
            if (record_count >= 1100) {
                record_count = 0;
                out.flush();
                out.close();
                out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
//                printHeader(out);
//                printCategory(props, prefix, out);
            }
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", phone.vendor);
            templates.put("\\$\\{brand\\.url\\}", phone.vendor);
            templates.put("\\$\\{url\\}", phone.vendor);
            Map<String, String> filteredProps = filterProps(props, templates);
//            printCategory(filteredProps, prefix + ".brand", out);
//            printPhone(filteredProps, phone, out, prefix);
        }
    }
*//*


    private static void printHeadsets(String brandName, Map<String, String> props, PrintStream out) throws IOException {
        List<Headset> headsets = Headset.parseHeadsets(brandName, 2);
        Map<String, String> templates = new HashMap<String, String>();
        templates.put("\\$\\{brand\\.name\\}", brandName);
        templates.put("\\$\\{url\\}", brandName);
        Map<String, String> filteredProps = filterProps(props, templates);
        printCategory("brandcat", filteredProps, out);
        templates = new HashMap<String, String>();
        for (Headset headset : headsets) {
            templates.put("\\$\\{brand\\.name\\}", headset.brandName);
            templates.put("\\$\\{art\\.name\\}", headset.name);
            templates.put("\\$\\{headset\\.vendor\\}", headset.brandName);
            templates.put("\\$\\{headset\\.name\\}", headset.brandName + " " + headset.model);
            templates.put("\\$\\{headset\\.url\\}", headset.brandName + "_" + headset.model);
            templates.put("\\$\\{headset\\.type\\}", headset.type);
            templates.put("\\$\\{headset\\.pin\\}", headset.pin);
            templates.put("\\$\\{device\\.reflist\\}", devicesToRef(headset, "Гарнитура", "Headset_"));
            filteredProps = filterProps(props, templates);
            printGoods(filteredProps, "art", out, headset.price, headset.oldPrice, headset.count);
            for (String model : headset.devices) {
                templates.put("\\$\\{model\\.name\\}", headset.brandName + " " + model);
                templates.put("\\$\\{model\\.url\\}", headset.brandName + "_" + model);
                filteredProps = filterProps(props, templates);
                printGoods(filteredProps, "model", out, headset.price, headset.oldPrice, headset.count);
            }
//            templates.put("\\$\\{art\\.name\\}", headset.name);
//            filteredProps = filterProps(props, templates);
//            for (String model : headset.devices) {
//                templates.put("\\$\\{headset\\.pin\\}", headset.pin);
//                templates.put("\\$\\{headset\\.vendor\\}", headset.vendor);
//                templates.put("\\$\\{model\\.type\\}", headset.type);
//                filteredProps = filterProps(props, templates);
//                printHeadset(filteredProps, headset, out);
//            }
        }
    }

    private static void printGoods(Map<String, String> filteredProps, String prefix, PrintStream out, int price, int oldPrice, int count) {
        CSVData data = new CSVData();
        data.engname = filteredProps.get(prefix + ".engname");
        data.name = filteredProps.get(prefix + ".name");
        data.id = filteredProps.get(prefix + ".id");
        data.desc = filteredProps.get(prefix + ".desc");
        data.shortDesc = filteredProps.get(prefix + ".shortdesc");
        data.sort = getSort();
        data.title = filteredProps.get(prefix + ".title");
        data.metaKeywords = filteredProps.get(prefix + ".meta.keywords");
        data.metaDesc = filteredProps.get(prefix + ".meta.desc");
        data.picture = filteredProps.get(prefix + ".photo");
        data.price = price + "";
        data.oldPrice = oldPrice + "";
        data.count = count + "";
        out.println(data);
    }

    private static void printRepairs(int price) throws BiffException, IOException {
        increaseCounter();
        Map<String, String> props = DataHelper.readProps("data/phones/remont.properties");
        String outPath = "data/import/phones-repair-price";
        String prefix = "remont";
        file_count = 0;
        record_count = 0;
        PrintStream out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
        List<Repair> phones = ExcelParser.parseRepair("data/phones/phones.xls", price);
        out.println(header);
        printCategory(prefix, props, out);
        List<String> processedModels = new ArrayList<String>();
        for (Repair phone : phones) {
            out = createNextFile(out, outPath, prefix, props);
            Map<String, String> filteredProps = filterProps(props, phone);
            printCategory(prefix + ".brand", filteredProps, out);
            out = printPhone(filteredProps, outPath, phone, out, prefix, processedModels);
        }
    }

    private static Map<String, String> filterProps(Map<String, String> props, Repair phone) {
        Map<String, String> templates = new HashMap<String, String>();
        templates.put("\\$\\{brand\\.name\\}", phone.vendor);
        templates.put("\\$\\{brand\\.url\\}", phone.vendor);
        templates.put("\\$\\{url\\}", phone.vendor);
        return filterProps(props, templates);
    }

    private static PrintStream createNextFile(PrintStream out, String outPath, String prefix, Map<String, String> props) throws FileNotFoundException {
        if (record_count >= 700) {
            record_count = 0;
            out.flush();
            out.close();
            out = new PrintStream(new FileOutputStream(outPath + "_" + file_count++ + ".txt"));
            out.println(header);
            printCategory(prefix, props, out);
            Map<String, String> filteredProps = filterProps(props, props);
            printCategory(prefix + ".brand", filteredProps, out);
        }
        return out;
    }

    private static Map<String, String> filterProps(Map<String, String> props, Map<String, String> templates) {
        Map<String, String> filteredProps = new HashMap<String, String>();
        for (String key : props.keySet()) {
            String value = props.get(key);
            for (String filterKey : templates.keySet()) {
                if (value.contains("url")) {
                    value = value.replaceAll(filterKey, templates.get(filterKey)).trim();
                    value = DataHelper.codeInURL(value);
                } else {
                    value = value.replaceAll(filterKey, templates.get(filterKey));
                }
                if (key.contains("photo")) {
                    value = value.toLowerCase();
                }
            }
            filteredProps.put(key, value);
        }
        return filteredProps;
    }


    private static PrintStream printPhone(Map<String, String> props, String outPath, Repair phone, PrintStream out, String prefix, List<String> processedModels) throws FileNotFoundException {
        for (String model : phone.models) {
            if (processedModels.contains(model)) {
                continue;
            }
            out = createNextFile(out, outPath, prefix, props);
            record_count++;
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{brand\\.name\\}", phone.vendor);
            templates.put("\\$\\{model\\.name\\}", model);
            templates.put("\\$\\{model\\.url\\}", phone.vendor + "_" + model);
            templates.put("\\$\\{price\\}", phone.price + "");
            Map<String, String> filteredProps = filterProps(props, templates);
            CSVData data = new CSVData();
            data.engname = filteredProps.get(prefix + ".model.engname");
            data.name = filteredProps.get(prefix + ".model.name");
            data.id = filteredProps.get(prefix + ".model.id");
            data.desc = filteredProps.get(prefix + ".model.desc");
            data.shortDesc = filteredProps.get(prefix + ".model.shortdesc");
            data.sort = getSort();
            data.title = filteredProps.get(prefix + ".model.title");
            data.metaKeywords = filteredProps.get(prefix + ".model.meta.keywords");
            data.metaDesc = filteredProps.get(prefix + ".model.meta.desc");
            data.picture = filteredProps.get(prefix + ".model.photo").toLowerCase();
            data.price = phone.price + "";
            data.oldPrice = phone.price + "";
            data.count = phone.count + "";
            out.println(data);
        }
        return out;
    }

    private static void printBodies(String brandName, Map<String, String> props, PrintStream out, double coef) throws IOException {
        printCategoryFiltered("bodies.brand", props, out, brandName);
        String fileName = brandName.toLowerCase() + ".txt";
        if (brandName.equals("Sony Ericsson")) {
            fileName = "se.txt";
        }
        List<Body> bodies = parseBodies("data/body/body." + fileName, coef);
        CSVData data = new CSVData();
        String category = "bodies.model";
        for (Body body : bodies) {
            data.engname = filterBody(props.get(category + ".engname"), body);
            data.name = filterBody(props.get(category + ".name"), body);
            data.id = filterBody(props.get(category + ".id"), body);
            data.price = body.price + "";
            data.oldPrice = body.oldPrice + "";
            data.count = body.count + "";
            data.desc = filterBody(props.get(category + ".desc"), body);
            data.shortDesc = filterBody(props.get(category + ".shortdesc"), body);
            data.sort = getSort();
            data.title = filterBody(props.get(category + ".title"), body);
            data.metaKeywords = filterBody(props.get(category + ".meta.keywords"), body);
            data.metaDesc = filterBody(props.get(category + ".meta.desc"), body);
            data.picture = filterBody(props.get(category + ".photo"), body);
            out.println(data);
        }
    }

    private static String filterBody(String value, Body body) {
        String result = value.replaceAll("\\$\\{brand\\.name\\}", body.brandName);
        result = result.replaceAll("\\$\\{model\\.name\\}", body.model);
        result = result.replaceAll("\\$\\{url\\}", DataHelper.codeInURL(body.model));
        return result;
    }


    private static List<Body> parseBodies(String path, double coef) throws IOException {
        List<Body> bodies = new ArrayList<Body>();
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line;
        while ((line = reader.readLine()) != null) {
            Body body = Body.parseBody(line, coef);
            bodies.add(body);
        }
        return bodies;
    }

    private static void printCategoryFiltered(String category, Map<String, String> props, PrintStream out, String brandName) {
        String cat = category + "." + brandName.toLowerCase();
        CSVData data = new CSVData();
        data.engname = filterName(props.get(category + ".engname"), brandName, false);
        data.name = filterName(props.get(category + ".name"), brandName, false);
        checkCatSort(data.name);
        data.id = filterUrl(props.get(category + ".id"), brandName);
        data.desc = filterName(props.get(category + ".desc"), brandName, false);
        data.shortDesc = filterName(props.get(category + ".shortdesc"), brandName, false);
        data.sort = catSort.get(data.name) + "";
        data.title = filterName(props.get(category + ".title"), brandName, true);
        data.metaKeywords = filterName(props.get(category + ".meta.keywords"), brandName, true);
        data.metaDesc = filterName(props.get(category + ".meta.desc"), brandName, true);
        out.println(data);
    }

    private static void printCategory(String category, Map<String, String> props, PrintStream out) {
        CSVData data = new CSVData();
        data.engname = props.get(category + ".engname");
        data.name = props.get(category + ".name");
        checkCatSort(data.name);
        data.id = props.get(category + ".id");
        data.desc = props.get(category + ".desc");
        data.shortDesc = props.get(category + ".shortdesc");
        data.sort = catSort.get(data.name) + "";
        data.title = props.get(category + ".title");
        data.metaKeywords = props.get(category + ".meta.keywords");
        data.metaDesc = props.get(category + ".meta.desc");
        data.picture = props.get(category + ".photo");
        out.println(data);
    }

    private static void printAccums(String path, String brandName, double coef, Map<String, String> props, boolean printModels, String outName, boolean split, PrintStream out) throws IOException {
        if (out == null) {
            out = new PrintStream(new FileOutputStream(outName + ".txt"));
            out.println(header.toString());
        }
        printCategory("accums", props, out);
        printCategoryFiltered("accums.brand", props, out, brandName.replace("Maxcell", ""));
        BufferedReader reader = new BufferedReader(new FileReader(path));
        List<Accum> accumsList = Accum.parseAccums(brandName, coef);
        reader.close();
        int count = 0;
        int fileCount = 0;
        for (Accum accum : accumsList) {
            count++;
            if (printModels) {
                accum.modelName = "";
            }
            accum.brandName = brandName.replace("Maxcell", "");

            String titleRus = props.get("accum.title");
            String descRus = props.get("accum.desc");
            String shortDescRus = props.get("accum.shortdesc");
            String metaDescRus = props.get("accum.meta.desc");
            String metaKeywordsRus = props.get("accum.meta.keywords");
            if (props.get("accum." + brandName.toLowerCase() + ".title") != null) {
                titleRus = props.get("accum." + brandName.toLowerCase() + ".title");
            }
            if (props.get("accum." + brandName.toLowerCase() + ".desc") != null) {
                descRus = props.get("accum." + brandName.toLowerCase() + ".desc");
            }
            if (props.get("accum." + brandName.toLowerCase() + ".shortdesc") != null) {
                shortDescRus = props.get("accum." + brandName.toLowerCase() + ".shortdesc");
            }
            if (props.get("accum." + brandName.toLowerCase() + ".meta.desc") != null) {
                metaDescRus = props.get("accum." + brandName.toLowerCase() + ".meta.desc");
            }
            if (props.get("accum." + brandName.toLowerCase() + ".meta.keywords") != null) {
                metaKeywordsRus = props.get("accum." + brandName.toLowerCase() + ".meta.keywords");
            }
            CSVData data = new CSVData();
            data.art = accum.art;
            data.engname = filterAccums(props.get("accum.engname"), accum, accumsList);
            data.name = filterAccums(props.get("accum.name"), accum, accumsList);
            if (data.name.contains("Maxcell") || data.name.contains("Craftmann")) {
                data.name = data.name.replace(" (оригинальный)", "");
            }
            data.id = DataHelper.codeInURL(filterAccums(props.get("accum.id"), accum, accumsList));
            data.price = accum.price + "";
            data.oldPrice = accum.oldPrice + "";
            data.count = accum.count + "";
            data.desc = filterAccums(descRus, accum, accumsList);
            data.shortDesc = filterAccums(shortDescRus, accum, accumsList);
            data.sort = getSort();
            data.title = filterAccums(titleRus, accum, accumsList);
            data.metaKeywords = filterAccums(metaKeywordsRus, accum, accumsList);
            data.metaDesc = filterAccums(metaDescRus, accum, accumsList);
            data.picture = filterAccums(props.get("accum.photo"), accum, accumsList);
            out.println(data);
        }
        List<String> processedModels = new ArrayList<String>();
        if (printModels) {
            for (Accum accum : accumsList) {
                if (count >= 145 && split) {
                    fileCount++;
                    count = 0;
                    out.close();
                    out = new PrintStream(new FileOutputStream(outName + "-" + fileCount + ".txt"));
                    out.println(header.toString());
                    printCategory("accums", props, out);
                    printCategoryFiltered("accums.brand", props, out, brandName.replace("Maxcell", ""));
                }
                accum.brandName = brandName;
                count += printModels(accum, props, accumsList, processedModels, out);
            }
        }
    }

    private static void increaseCounter() {
        increaseCounter(1);
    }

    private static void increaseCounter(int coef) {
        catCount += 1000 * coef;
        counter = 0;
    }

    private static int printModels(Accum accum, Map<String, String> accums, List<Accum> accumsList, List<String> processedModels, PrintStream out) throws IOException {
        int count = 0;
        for (String device : accum.devices) {
            if (processedModels.contains(device)) {
                System.out.println("Processed model: " + device);
                continue;
            }
            count++;
            accum.modelName = accum.brandName + " " + device;
            String titleRus = accums.get("accum.model.title");
            String descRus = accums.get("accum.model.desc");
            String shortDescRus = accums.get("accum.model.shortdesc");
            String metaDescRus = accums.get("accum.model.meta.desc");
            String metaKeywordsRus = accums.get("accum.model.meta.keywords");
            if (accums.get("accum.model." + accum.brandName.toLowerCase() + ".title") != null) {
                titleRus = accums.get("accum.model." + accum.brandName.toLowerCase() + ".title");
            }
            if (accums.get("accum.model." + accum.brandName.toLowerCase() + ".desc") != null) {
                descRus = accums.get("accum.model." + accum.brandName.toLowerCase() + ".desc");
            }
            if (accums.get("accum.model." + accum.brandName.toLowerCase() + ".shortdesc") != null) {
                shortDescRus = accums.get("accum.model." + accum.brandName.toLowerCase() + ".shortdesc");
            }
            if (accums.get("accum.model." + accum.brandName.toLowerCase() + ".meta.desc") != null) {
                metaDescRus = accums.get("accum.model." + accum.brandName.toLowerCase() + ".meta.desc");
            }
            if (accums.get("accum.model." + accum.brandName.toLowerCase() + ".meta.keywords") != null) {
                metaKeywordsRus = accums.get("accum.model." + accum.brandName.toLowerCase() + ".meta.keywords");
            }
            CSVData data = new CSVData();
            data.art = accum.art;
            data.engname = filterAccums(accums.get("accum.model.engname"), accum, accumsList);
            data.name = filterAccums(accums.get("accum.model.name"), accum, accumsList);
            data.id = DataHelper.codeInURL(filterAccums(accums.get("accum.model.id"), accum, accumsList));
            data.price = accum.price + "";
            data.oldPrice = accum.oldPrice + "";
            data.count = accum.count + "";
            data.desc = filterAccums(descRus, accum, accumsList);
            data.desc = filterOrders(data.desc, accum.brandName, device);
            data.shortDesc = filterAccums(shortDescRus, accum, accumsList);
            data.sort = getSort();
            data.title = filterAccums(titleRus, accum, accumsList);
            data.metaKeywords = filterAccums(metaKeywordsRus, accum, accumsList);
            data.metaDesc = filterAccums(metaDescRus, accum, accumsList);
            data.picture = filterAccums(accums.get("accums.model.photo"), accum, accumsList);
            out.println(data);
            processedModels.add(device);
        }
        return count;
    }

    private static String filterOrders(String desc, String brand, String model) throws IOException {
//        if (!(brand.equals("Nokia") ||
//                brand.equals("Samsung") ||
//                brand.equals("Sony Ericsson"))) {
        if (!(brand.equalsIgnoreCase("blackberry") || brand.equalsIgnoreCase("htc") || brand.equalsIgnoreCase("nokia") || brand.equalsIgnoreCase("sony ericsson"))) {
            return desc.replaceAll("\\$\\{order\\.list\\}", "");
//            <h2>Что заказывают вместе с аккумулятором ${model.name}?</h2>${order.list}\
        }

        StringBuilder sb = new StringBuilder("<div class=\"cpt_category_tree\"><h2>Что покупают вместе с аккумулятором " + brand + " " + model + "?</h2><ul>");
//        Charger charger = parseCharger(1, false, brand);
//        sb.append("<li><a href=\"").append(DataHelper.codeInURL(String.format(Charger.AAA_URL_NETWORK, brand))).append("\"> Сетевое зарядное устройство ").append(brand + " " + model).append("</a>").append(" за <strong>").append(charger.price).append("р.</strong></li>");
//        charger = parseCharger(1, true, brand);
//        sb.append("<li><a href=\"").append(DataHelper.codeInURL(String.format(Charger.AAA_URL_NETWORK, brand))).append("\"> Автомобильное зарядное устройство ").append(brand + " " + model).append("</a>").append(" за <strong>").append(charger.price).append("р.</strong></li></ul>");
        sb.append("<li class=\"parent\"><a style=\"font-weight:bold\" href=\"").append(DataHelper.codeInURL(Charger.ORIG_URL_NETWORK + brand + "_" + model)).append("\">Оригинальное СЗУ ").append(brand + " " + model).append("</a>").append(" за <span style=\"color:red\">").append(Charger.getPrice(brand, model, false)).append(" руб.</span></li>");
        sb.append("<li class=\"parent\"><a style=\"font-weight:bold\" href=\"").append(DataHelper.codeInURL(Charger.ORIG_URL_AUTO + brand + "_" + model)).append("\">Оригинальное АЗУ ").append(brand + " " + model).append("</a>").append(" за <span style=\"color:red\">").append(Charger.getPrice(brand, model, true)).append(" руб.</span></li></ul></div>");
        return desc.replaceAll("\\$\\{order\\.list\\}", sb.toString());
    }

    private static void printChargers(String category, String brandName, Map<String, String> props, PrintStream out, int columns, double coef, boolean auto) throws IOException {
        if (brandName.equalsIgnoreCase("nokia") ||
                brandName.equalsIgnoreCase("samsung") ||
                brandName.equalsIgnoreCase("sony ericsson") ||
                brandName.equalsIgnoreCase("htc") ||
                brandName.equalsIgnoreCase("blackberry")) {
            printOrigChargers(category.replace(".auto", "").replace(".network", "") + ".orig", brandName, props, out, columns, coef, auto);
        }
        if (brandName.equalsIgnoreCase("blackberry") || brandName.equalsIgnoreCase("htc")) {
            return;
        }
        boolean isAuto = category.contains("auto");
        Charger charger = parseCharger(props.get(category + "." + brandName.toLowerCase().replace("sony ericsson", "se") + ".data"), coef, isAuto, brandName);
        CSVData data = new CSVData();
        data.engname = filterChargers(category, props, props.get(category + ".brand.engname"), charger, columns);
        data.name = filterChargers(category, props, props.get(category + ".brand.name"), charger, columns);
        data.id = filterChargers(category, props, props.get(category + ".brand.id"), charger, columns);
        data.price = charger.price + "";
        data.oldPrice = charger.oldPrice + "";
        data.count = charger.count + "";
        data.desc = filterChargers(category, props, props.get(category + ".brand.desc"), charger, columns);
        data.shortDesc = filterChargers(category, props, props.get(category + ".brand.shortdesc"), charger, columns);
        data.sort = getSort();
        data.title = filterChargers(category, props, props.get(category + ".brand.title"), charger, columns);
        data.metaKeywords = filterChargers(category, props, props.get(category + ".brand.meta.keywords"), charger, columns);
        data.metaDesc = filterChargers(category, props, props.get(category + ".brand.meta.desc"), charger, columns);
        data.picture = filterChargers(category, props, props.get(category + ".brand.photo"), charger, columns);
        out.println(data);
    }

    private static String getSort() {
        return catCount + counter++ + "";
    }

    private static void printOrigChargers(String category, String brandName, Map<String, String> props, PrintStream out, int columns, double coef, boolean auto) throws IOException {
        String typeData = auto ? "car." : "";
        String path = props.get("chargers.orig.data").replaceAll("\\$\\{type\\.data\\}", typeData);
//        List<Charger> chargers = parseOrigChargers(filterName(props.get(category + ".data"), brandName.replace("Sony Ericsson", "se").toLowerCase(), false), coef, brandName, auto);
        List<Charger> chargers = parseOrigChargers(filterName(path, brandName.replace("Sony Ericsson", "se").toLowerCase(), false), coef, brandName, auto);
        CSVData data = new CSVData();
        for (Charger charger : chargers) {
            Map<String, String> templates = new HashMap<String, String>();
            templates.put("\\$\\{name\\}", charger.name);
            templates.put("\\$\\{brand\\.name\\}", charger.brandName);
            templates.put("\\$\\{type\\}", charger.type);
            templates.put("\\$\\{engtype\\}", charger.typeUrl);
            templates.put("\\$\\{type\\.url\\}", charger.typeUrl);
            templates.put("\\$\\{charger\\.name\\}", charger.name);
            templates.put("\\$\\{name\\.url\\}", DataHelper.codeInURL(charger.name));
            templates.put("\\$\\{vendor\\}", charger.brandName);
            templates.put("\\$\\{model\\}", charger.model);
            templates.put("\\$\\{device\\.shortlist\\}", devicesToShortDesc(charger.models));
            templates.put("\\$\\{device\\.titlelist\\}", devicesToTitle(charger.models));
            templates.put("\\$\\{model\\.table\\}", modelsToTableURL(charger.models, charger.modelURLs, charger.brandName, charger.prefix, columns));

            Map<String, String> filteredProps = DataGenerator.filterProps(props, templates, "chargers.orig");
            printChargers(out, data, charger, filteredProps);
//            data.engname = filterChargers(category, props, props.get(category + ".engname"), charger, columns);
//            data.name = filterChargers(category, props, props.get(category + ".name"), charger, columns);
//            data.id = filterChargers(category, props, props.get(category + ".id"), charger, columns);
//            data.price = charger.price + "";
//            data.oldPrice = charger.oldPrice + "";
//            data.count = charger.count + "";
//            data.desc = filterChargers(category, props, props.get(category + ".desc"), charger, columns);
//            data.shortDesc = filterChargers(category, props, props.get(category + ".shortdesc"), charger, columns);
//            data.sort = getSort();
//            data.title = filterChargers(category, props, props.get(category + ".title"), charger, columns);
//            data.metaKeywords = filterChargers(category, props, props.get(category + ".meta.keywords"), charger, columns);
//            data.metaDesc = filterChargers(category, props, props.get(category + ".meta.desc"), charger, columns);
//            data.picture = filterChargers(category, props, props.get(category + ".photo"), charger, columns);
//            out.println(data);
//            int i = 0;
            for (String model : charger.models) {
                String name = charger.brandName + " " + model;
                templates.put("\\$\\{name\\}", name);
                templates.put("\\$\\{name\\.url\\}", name);
                templates.put("\\$\\{model\\.table\\}", getLink(charger.prefix + " " + charger.name, charger.url));
                templates.put("\\$\\{device\\.shortlist\\}", "");
                templates.put("\\$\\{device\\.titlelist\\}", "");
                filteredProps = DataGenerator.filterProps(props, templates, "chargers.orig");
                printChargers(out, data, charger, filteredProps);
            }
        }
    }

    private static String getLink(String text, String url) {
        return "<a href=\"" + url + "\">" + text + "</a>";
    }

    private static void printChargers(PrintStream out, CSVData data, Charger charger, Map<String, String> filteredProps) {
        data.engname = filteredProps.get("chargers.orig.engname");
        data.name = filteredProps.get("chargers.orig.name");
        data.id = filteredProps.get("chargers.orig.id");
        data.desc = filteredProps.get("chargers.orig.desc");
        data.shortDesc = filteredProps.get("chargers.orig.shortdesc");
        data.sort = getSort();
        data.title = filteredProps.get("chargers.orig.title");
        data.metaKeywords = filteredProps.get("chargers.orig.meta.keywords");
        data.metaDesc = filteredProps.get("chargers.orig.meta.desc");
        data.picture = filteredProps.get("chargers.orig.photo");
        data.price = charger.price + "";
        data.oldPrice = charger.oldPrice + "";
        data.count = charger.count + "";
        out.println(data);
    }

    private static String filterName(String value, String name, boolean translit) {
        if (translit) {
            String transName = Helper.translit(name);
            name = name + " " + transName;
        }
        return value.replaceAll("\\$\\{brand\\.name\\}", name);
    }

    private static String filterUrl(String value, String name) {
        return value.replaceAll("\\$\\{url\\}", DataHelper.codeInURL(name));
    }

    private static Charger parseCharger(double coef, boolean isAuto, String brandName) throws IOException {
//        parseCharger(props.get(category + "." + brandName.toLowerCase().replace("sony ericsson", "se") + ".data"), coef, isAuto, brandName);
        return parseCharger("data/chargers/charger." + brandName.replace("Sony Ericsson", "se") + ".txt", coef, isAuto, brandName);
    }

    private static Charger parseCharger(String path, double coef, boolean isAuto, String brandName) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        Charger charger = new Charger();
        String[] line = reader.readLine().split(";");
        int price;
        if (isAuto) {
            price = Integer.valueOf(line[2]);
        } else {
            price = Integer.valueOf(line[1]);
        }
        String[] models = line[0].split(",");
        int count = Integer.valueOf(line[3]);
        int oldPrice = (int) (price * coef);
        charger.brandName = brandName;
        charger.count = count;
        charger.price = price;
        charger.oldPrice = oldPrice;
        charger.models = models;
        return charger;
    }

    private static List<Charger> parseOrigChargers(String path, double coef, String brandName, boolean auto) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        List<Charger> chargers = new ArrayList<Charger>();
        String line;
        while ((line = reader.readLine()) != null) {
            Charger charger = Charger.parseCharger(line, coef, auto);
            chargers.add(charger);
        }
        return chargers;
    }

    private static String filterChargers(String category, Map props, String value, Charger charger, int columns) {
        String result = value.replaceAll("\\$\\{brand\\.name\\}", charger.brandName);
        if (charger.name != null) {
            result = result.replaceAll("\\$\\{name\\}", charger.name);
            result = result.replaceAll("\\$\\{type\\}", charger.type);
            result = result.replaceAll("\\$\\{type\\.url\\}", charger.typeUrl);
            result = result.replaceAll("\\$\\{charger\\.name\\}", charger.name);
            result = result.replaceAll("\\$\\{name\\.url\\}", DataHelper.codeInURL(charger.name));
            result = result.replaceAll("\\$\\{vendor\\}", charger.brandName);
            result = result.replaceAll("\\$\\{model\\}", charger.model);
            result = result.replaceAll("\\$\\{device\\.shortlist\\}", devicesToShortDesc(charger.models));
            result = result.replaceAll("\\$\\{device\\.titlelist\\}", devicesToTitle(charger.models));
        }
        result = result.replaceAll("\\$\\{brand\\.name\\.url\\}", DataHelper.codeInURL(charger.brandName));
        result = result.replaceAll("\\$\\{brand\\.name\\.photo\\}", charger.brandName.replace("Sony Ericsson", "se").toLowerCase());
        result = result.replaceAll("\\$\\{model\\.table\\}", modelsToTable(charger.models, charger.brandName, columns));
        result = result.replaceAll("\\$\\{brand\\.title\\}", (String) props.get(category + "." + charger.brandName.toLowerCase().replace("sony ericsson", "se") + ".title"));
        result = result.replaceAll("\\$\\{brand\\.keywords\\}", (String) props.get(category + "." + charger.brandName.toLowerCase().replace("sony ericsson", "se") + ".keywords"));
        return result;
    }

    public static String modelsToTableURL(String[] models, List<String> urls, String name, String prefix, int columns) {
        StringBuilder sb = new StringBuilder("<table style=\"font-size:12px\">");
        for (int i = 1; i <= models.length; i++) {
            if (i == 1 && i % columns + 1 == 0) {
                sb.append("<tr>");
            }
            sb.append("<td width=\"150\"><strong><a href=\"").append(urls.get(i - 1)).append("\">").append(prefix).append(" ").append(name).append(" ").append(models[i - 1]).append("</a></strong></td>");
            if (i % columns == 0) {
                sb.append("</tr>");
            }
        }
        if (sb.toString().endsWith("</td>")) {
            sb.append("</tr>");
        }
        sb.append("</table>");
        return sb.toString();
    }

    public static String modelsToTable(String[] models, String name, int columns) {
        StringBuilder sb = new StringBuilder("<table style=\"font-size:12px\">");
        for (int i = 1; i <= models.length; i++) {
            if (i == 1 && i % columns + 1 == 0) {
                sb.append("<tr>");
            }
            sb.append("<td width=\"150\"><strong>").append(name).append(" ").append(models[i - 1]).append("</strong></td>");
            if (i % columns == 0) {
                sb.append("</tr>");
            }
        }
        if (sb.toString().endsWith("</td>")) {
            sb.append("</tr>");
        }
        sb.append("</table>");
        return sb.toString();

    }

    private static String filterAccums(String value, Accum accum, List<Accum> accumsList) {
        String result = value.replaceAll("\\$\\{accum\\.name\\}", accum.name);
        result = result.replaceAll("\\$\\{accum\\.table\\}", accumsTableRus(accum, accumsList));
        result = result.replaceAll("\\$\\{brand\\.name\\}", accum.brandName);
        result = result.replaceAll("\\$\\{brand\\.name\\.translit}", Helper.translit(accum.brandName));
        result = result.replaceAll("\\$\\{model\\.name\\}", accum.modelName);
        result = result.replaceAll("\\$\\{accum\\.name\\.orig\\}", accum.name.replace("Maxcell ", ""));
        result = result.replaceAll("\\$\\{accum\\.name\\.url\\}", DataHelper.codeInURL(accum.name));
        result = result.replaceAll("\\$\\{accum\\.name\\.orig\\.url\\}", DataHelper.codeInURL(accum.name.replace("Maxcell ", "")));
        result = result.replaceAll("\\$\\{brand\\.name\\.translitUrl\\}", Helper.backTranslitUrl(accum.brandName));
        result = result.replaceAll("\\$\\{accum\\.vendor\\}", accum.vendor);
        result = result.replaceAll("\\$\\{accum\\.model\\}", accum.model);
        result = result.replaceAll("\\$\\{accum\\.power\\}", accum.power);
        result = result.replaceAll("\\$\\{accum\\.volt\\}", accum.volt);
        result = result.replaceAll("\\$\\{accum\\.type\\}", accum.type);
        result = result.replaceAll("\\$\\{device\\.titlelist\\}", devicesToTitle(accum.devices));
        result = result.replaceAll("\\$\\{device\\.desclist\\}", devicesToDesc(accum.devices, accum.brandName.replace("Maxcell", "")));
        result = result.replaceAll("\\$\\{device\\.shortlist\\}", devicesToShortDesc(accum.devices));
        result = result.replaceAll("\\$\\{device\\.reflist\\}", devicesToRefRus(accum));
        return result;
    }

    private static String accumsTableRus(Accum accum, List<Accum> accumsList) {
        return accumsTable(accum, accumsList, "Аккумулятор ", "");
    }

    private static String accumsTable(Accum accum, List<Accum> accumsList, String name, String prefix) {
        StringBuilder sb = new StringBuilder("<table style=\"font-size:13px\">");
        int count = 1;
        for (int i = 1; i < accumsList.size(); i++, count++) {
            if (i == 1 || (i % COLUMNS) + 1 == 0) {
                sb.append("<tr>");
            }
            if (accumsList.get(i - 1).equals(accum)) {
                count--;
                continue;
            }
            String accumName = accumsList.get(i - 1).name.toLowerCase().replaceAll("-", " ");
            String accumUrl = ("Accumulator_" + DataHelper.codeInURL(accumsList.get(i - 1).name));
            sb.append("<td style=\"padding:0 20 10 0\"><strong><a href=\"http://extramobi.ru/").append(prefix).append("product/").append(accumUrl).append("\">").append(accumName).append("</a></strong></td>");
            if (count % COLUMNS == 0) {
                sb.append("</tr>");
            }
        }
        if (sb.toString().endsWith("</td>")) {
            sb.append("</tr>");
        }
        sb.append("</table>");
        return sb.toString();
    }

    private static String devicesToRef(Headset headset, String name, String urlPrefix) {
        if (headset.devices.length > 10) {
            return devicesToTableRef(headset, name, 4, urlPrefix);
        }
        StringBuilder sb = new StringBuilder("<ul>");
        for (String device : headset.devices) {
            String deviceName = name + " " + headset.brandName + " " + device;
            String deviceUrl = DataHelper.codeInURL(headset.brandName) + "_" + DataHelper.codeInURL(device);
            if (deviceUrl.equals(DataHelper.codeInURL(headset.model))) continue;
            sb.append("<li><strong><a href=\"http://extramobi.ru/").append("product/").append(urlPrefix).append(deviceUrl).append("\">").append(deviceName).append("</a></strong></li>");
        }
        sb.append("</ul><br/>");
        return sb.toString();
    }

    public static String devicesToTableRef(Headset headset, String name, int columns, String urlPrefix) {
        StringBuilder sb = new StringBuilder("<table style=\"font-size:13px\">");
        for (int i = 1; i <= headset.devices.length; i++) {
            if (i == 1 && i % columns + 1 == 0) {
                sb.append("<tr>");
            }
            String device = headset.devices[i - 1];
            String deviceName = name + " " + headset.brandName + " " + device;
            String deviceUrl = DataHelper.codeInURL(headset.brandName) + "_" + DataHelper.codeInURL(device);
//            sb.append("<td width=\"150\"><strong>").append(name).append(" ").append(models[i - 1]).append("</strong></td>");
            sb.append("<td width=\"200\"><strong><a href=\"http://extramobi.ru/").append("product/").append(urlPrefix).append(deviceUrl).append("\">").append(deviceName).append("</a></strong></td>");

            if (i % columns == 0) {
                sb.append("</tr>");
            }
        }
        if (sb.toString().endsWith("</td>")) {
            sb.append("</tr>");
        }
        sb.append("</table>");
        return sb.toString();
    }

    private static String devicesToRef(Accum accum, String name, String suffix) {
        if (accum.modelName == null) return devicesToDesc(accum.devices, accum.brandName);
        StringBuilder sb = new StringBuilder("<ul>");
        for (String device : accum.devices) {
            String deviceName = name + accum.brandName + " " + device;
            String deviceUrl = DataHelper.codeInURL(accum.brandName) + "_" + DataHelper.codeInURL(device);
            if (deviceUrl.equals(DataHelper.codeInURL(accum.modelName))) continue;
            sb.append("<li><a href=\"http://extramobi.ru/").append(suffix).append("product/Accumulator_").append(deviceUrl).append("\">").append(deviceName).append("</a></li>");
        }
        sb.append("</ul><br/>");
        return sb.toString();
    }

    private static String devicesToRefRus(Accum accum) {
        return devicesToRef(accum, "Аккумулятор ", "");
    }

    private static String devicesToTitle(String[] devices) {
        StringBuilder sb = new StringBuilder();
        for (String device : devices) {
            sb.append(" ").append(device);
        }
        sb.delete(0, 1);
        return sb.toString();
    }

    public static String devicesToDesc(String[] devices, String brandName) {
        StringBuilder sb = new StringBuilder("<ul>");
        for (String device : devices) {
            String item = "<li><strong>" + brandName.replace("Craftmann", "") + " " + device + "</strong></li>";
            sb.append(item);
        }
        sb.append("</ul><br/>");
        return sb.toString();
    }


    public static String devicesToShortDesc(String[] devices) {
        StringBuilder sb = new StringBuilder();
        for (String device : devices) {
            sb.append(", <strong>").append(device).append("</strong>");
        }
        sb.deleteCharAt(0);
        return sb.toString();
    }
*/
}

